export function usePage(api, params = ref({})) {
    const defaultPageQuery = {
        pageIndex: 1,
        pageSize: 20
    }
    
    const defaultPageResult = {
        data: [],
        totalCount: 0,
        totalPages: 0
    }
    
    const loading = ref(false)
    const copyObj = obj => JSON.parse(JSON.stringify(obj))
    const pageQuery = ref(copyObj(defaultPageQuery))
    const pageResult = ref(copyObj(defaultPageResult))
    
    const load = async () => {
        loading.value = true
        const data = {...pageQuery.value, ...params.value}
        const res = await api(data)
        if (res.success) {
            const _pageResult = res.data
            const data = _pageResult.data || []
            _pageResult.data = pageResult.value.data.concat(data)
            pageResult.value = _pageResult
        } else {
            pageResult.value = copyObj(defaultPageResult)
        }
        loading.value = false
    }
    
    const hasMore = computed(() => {
        return pageQuery.value.pageIndex < pageResult.value.totalPages
    })
    
    const more = async () => {
        if (hasMore.value) {
            pageQuery.value.pageIndex++
            await load()
        }
    }
    
    const reload = async () => {
        pageQuery.value = copyObj(defaultPageQuery)
        pageResult.value = copyObj(defaultPageResult)
        await load()
    }
    
    return {pageQuery, pageResult, reload, load, more, loading, hasMore}
}
